package com.oh.iris.server;

import com.oh.core.common.base.MessageService;
import com.oh.core.common.constant.CommandEnum;
import com.oh.core.common.utils.MessageUtils;
import com.oh.core.common.utils.ServiceRouteFactory;
import com.oh.core.entity.MessageEntity;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;

/**
 * 消息处理类
 */
@Service
public class HandleMessageService implements MessageService, InitializingBean {

    private final Logger log = LoggerFactory.getLogger(HandleMessageService.class);

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    @Override
    public int handle(ChannelHandlerContext ctx, MessageEntity msg) {
        byte [] body = msg.getBody();
        log.info("默认转换成字符串：{}", new String(body));
        String str = ctx.channel().id().asLongText() + ": 你好！服务器转发一条消息！！";
        MessageUtils.sendMsgToAll(str.getBytes());
        ctx.fireChannelRead(msg); // 透传
        return 0;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ServiceRouteFactory.register(CommandEnum.MESSAGE_REQUEST.getCommand(), this);
    }
}
